package com.huntmobi.springsecuritydemo.base.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huntmobi.springsecuritydemo.base.enums.ContextTypeEnum;
import com.huntmobi.springsecuritydemo.base.enums.HttpEnum;
import com.huntmobi.springsecuritydemo.base.http.Request;
import com.huntmobi.springsecuritydemo.base.http.Response;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>
 *
 * @Author：zouzhimin
 * @description：防止用户没有登录，直接访问接口，不想返回html给用户，直接放回对应的json数据到前端
 * @date：crealed in 11:42 2020/7/7
 * </P>
 **/
@Component
public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException authException) throws IOException, ServletException {
        httpServletResponse.setContentType(ContextTypeEnum.JSONUTF8.getContextType());
        PrintWriter out = httpServletResponse.getWriter();
        Request request = Response.error(HttpEnum.ACCESSFAILED.getCode(),HttpEnum.ACCESSFAILED.getMsg());
        out.write(new ObjectMapper().writeValueAsString(request));
        out.flush();
        out.close();
    }
}
